import { reroute } from "../navigations/reroute";
import { BOOTSTRAPPING, LOADING_SPURCE_CODE, MOUNTED, NOT_BOOTSTRAPPED, NOT_LOAED, NOT_MOUNTED, shouldBeActive } from "./app.helper";

import '../navigations/route-event'
 /** 用来存放所有的应用 */
 let apps = []

/**
 * 
 * @param {*} appName   当前注册应用的名字
 * @param {*} loadApp   加载函数(必须返回的是promise)，返回的结果必须包含bootstrap、mount和 unmount做为接入协议
 * @param {*} activeFn  激活条件，满足条件时调用loadApp方法
 * @param {*} customProps  自定义属性可用于父子应用通信
 */
export function registerApplication(appName,loadApp,activeFn,customProps){
  apps.push({
    name: appName,
    loadApp: loadApp,
    activeFn: activeFn,
    customProps: customProps,
    status: NOT_LOAED
    
  });
  reroute()
}

export function getAppChanges(){
  /** 需要加载的应用 */
  const appsToLoad = []
  /** 需要挂载的应用 */
  const appsToMount = []
  /** 需要卸载的应用 */
  const appsToUnmount = []
  apps.forEach(app => {
    const appShouldBeActive = shouldBeActive(app)
    switch (app.status) {
      case NOT_LOAED:
      case LOADING_SPURCE_CODE:
        if(appShouldBeActive){
          appsToLoad.push(app)
        }
        break;
      case NOT_BOOTSTRAPPED:
      case BOOTSTRAPPING:
      case NOT_MOUNTED:
        if(appShouldBeActive){
          appsToMount.push(app)
        }
        break;
      case MOUNTED:
        if(!appShouldBeActive){
          appsToUnmount.push(app)
        }
        break;
    }
  })
  return {
    appsToLoad,appsToMount,appsToUnmount
  }
}
